import { request } from '@/api/request';
import { YmResponseCode } from '@/api/request/core';
import { getCurrToken } from '@/utils';
import { App } from 'antd';
import { AxiosError } from 'axios';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

/**
 * @deprecated   0710 废弃
 */
function useRequestInterceptors() {
  const navigate = useNavigate();
  const { message } = App.useApp();
  useEffect(() => {
    // console.log('--子路由切换 父级useEffect[]只会执行一次--');
    const resId = request.interceptors.response.use(
      function (response) {
        // console.log('--interceptors.response--value.3--', response)
        return response;
      },
      (err: unknown) => {
        // 登陆没成功就直接走登陆页面
        if (err instanceof AxiosError) {
          if (err.code === YmResponseCode.noRoot) {
            // 自己处理登出逻辑
            if (window.__POWERED_BY_QIANKUN__) {
              // 微应用
              message.error('登录过期，请重新登录');
            } else {
              console.log('--token过期--请重新登录---');
              navigate('/login');
            }
          }
          // console.log('--MyInit--request--err---:', err);
          if ((err.config as any).autoShowErrorMessage) {
            message.error(err.message);
          }

          return Promise.reject(err);
        }
      },
    );
    console.log('---主应用切换进子应用--getCurrToken()--：', getCurrToken());

    const reqId = request.interceptors.request.use((config) => {
      config.headers['Authorization'] = getCurrToken();
      return config;
    });

    return () => {
      console.log('---主应用切换出子应用----');
      request.interceptors.request.eject(reqId);
      request.interceptors.response.eject(resId);
    };
  }, []);
}

export default useRequestInterceptors;
